package com.yunzai.secure.handler;

import com.yunzai.generic.domain.JSONResult;
import com.yunzai.secure.service.ITokenService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class YunzaiLogoutSuccessHandler implements LogoutSuccessHandler {

    @Value("${token.authorization}")
    private String authorization;

    @Autowired
    private ITokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        Object attribute = request.getHeader(authorization);
        if (attribute != null) {
            String token = attribute.toString().substring("Bearer ".length(), attribute.toString().length() - 1);
            tokenService.invalidate(token);
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONResult.success().toString());
        response.flushBuffer(); // 确保响应立即发送
    }
}
